package com.augurit.gzcgwsp.sendNotice.service.impl;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.augurit.common.base.extmodel.BasicCombo;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.syslog.tool.SysTraceLogWriter;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.printDoc.service.IYwPrintDocService;
import com.augurit.gzcgwsp.sendNotice.dao.YwWebserviceForWbDao;
import com.augurit.gzcgwsp.sendNotice.entity.YwWebserviceForWb;
import com.augurit.gzcgwsp.sendNotice.entity.YwZhengwuInfo;
import com.augurit.gzcgwsp.sendNotice.foresee.gzcgw.webservice.util.WSInvoker;
import com.augurit.gzcgwsp.sendNotice.service.IYwWebserviceForWbService;
import com.augurit.gzcgwsp.sendNotice.web.form.YwWebserviceForWbForm;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.gzcgwsp.wfex.common.util.WfUtilsEX;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjclService;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjcllistService;
import com.augurit.wf.common.service.impl.WfBusClientServiceImpl;
import com.foresee.spiderweb.console.security.bean.ServiceResult;

/**
 * 网办（受理、办结），webservice方式交换给方欣
 * @author adm
 *
 */
@Service
@Transactional
public class YwWebserviceForWbServiceImpl extends WfBusClientServiceImpl<YwWebserviceForWbForm>  implements IYwWebserviceForWbService {
	Logger logger = (Logger) LoggerFactory.getLogger(YwWebserviceForWbServiceImpl.class);
	SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	private YwWebserviceForWbDao ywWebserviceForWbDao;
	@Autowired
	private IYwComSjcllistService ywComSjcllistService;
	@Autowired
	private IYwComSjclService ywComSjclService;
	@Autowired
	private IYwPrintDocService ywPrintDocService;
	@Autowired
	private IWfServiceEX wfServiceEX;
	
	@Override
	public void changState(long id) {
		ywWebserviceForWbDao.changState(id);
	}

	@Override
	public List<BasicCombo> getSphjdmmc() {
		
		return null;
	}

	@Override
	public List<BasicCombo> getXmmc() {
		
		return null;
	}

	@Override
	public void save(YwWebserviceForWb ywWebserviceForWb) {
		ywWebserviceForWbDao.save(ywWebserviceForWb);
	}

	@Override
	public Page<YwWebserviceForWbForm> searchPage(Page<YwWebserviceForWbForm> page, Map map) {
		
		return null;
	}

	@Override
	public Page<YwWebserviceForWbForm> search(Page<YwWebserviceForWbForm> page,List<PropertyFilter> filters) {
		
		return null;
	}

	@Override
	public Page<YwWebserviceForWbForm> search(Page<YwWebserviceForWbForm> page,YwWebserviceForWbForm form) {
		
		return null;
	}

	@Override
	public void delete(Long... ids) {
				
	}

	@Override
	public YwWebserviceForWbForm get(Long id) {
		
		return null;
	}

	@Override
	public void save(YwWebserviceForWbForm... forms) {
		
		
	}

	@Override
	public void save(YwWebserviceForWbForm forms) {
				
	}
	/**
	 * 根据acceptNo和link查询数据库中是否已经有记录
	 * @param acceptNo
	 * @param link
	 * @return
	 */
	public YwWebserviceForWb getYwWebserviceForWbByAcceptNoAndLink(String acceptNo,String link){
		String sphjmc = "";
		if("001".equals(link)){
			sphjmc = "受理";
		}else{
			sphjmc = "办结";
		}
		String hql = "from YwWebserviceForWb t where t.acceptNo='"+acceptNo+"' and t.sphjmc='"+sphjmc+"'";
		List<YwWebserviceForWb> list = ywWebserviceForWbDao.find(hql);
		if(list != null && list.size() > 0){
			return list.get(0);
		}
		return null;
	}
	/**
	 * 设置值和保存YwWebserviceForWb
	 * @param loginusername
	 * @param templateCode
	 * @param masterEntityKey
	 * @param durationExpression
	 * @param link
	 * @param bslyy
	 * @param map
	 */
	public void setValueAndSaveYwWebserviceForWb(String loginusername,String templateCode,String masterEntityKey,
			String durationExpression,String link ,String bslyy,Map<String,String> map){
		System.out.println("link ====================== "+link);
		if("001".equals(link) || "005".equals(link)){
			YwWebserviceForWb ywWebserviceForWb = null;
			YwWebserviceForWb ywWebserviceForWbExist = this.getYwWebserviceForWbByAcceptNoAndLink((String)map.get("acceptNo"), link);
			if(ywWebserviceForWbExist != null){//数据库中存在的，就把它取出来，避免有重复记录。
				ywWebserviceForWb = ywWebserviceForWbExist;
			}else{//否则new一个。
				ywWebserviceForWb = new YwWebserviceForWb();
			}
			ywWebserviceForWb.setContentid((String)map.get("approvalNo"));
			ywWebserviceForWb.setSjbbh(ywWebserviceForWb.getSjbbh() + 1);//数据版本号，每次都加1.
			ywWebserviceForWb.setProduceDate(new Date());
			ywWebserviceForWb.setAcceptNo((String)map.get("acceptNo"));
			SysCodeForm sysCodeForm = wfServiceEX.getItemNameByItemCodeAndTypeCode(templateCode, "JK_WB_FX");
			ywWebserviceForWb.setSxmc(sysCodeForm.getItemMemo());//项目名称
			ywWebserviceForWb.setWjsxbm(sysCodeForm.getItemName());//委局事项编码
			ywWebserviceForWb.setWjbh(wfServiceEX.getItemNameByItemCodeAndTypeCode("wjbh", "JK_WB_FX").getItemName());//委局编号
			ywWebserviceForWb.setZhxgsj(new Date());//最后修改时间
			if(!"Y".equals((String)map.get("sendNotice"))){//系统窗口收案，需要把申请部分的信息补上
				ywWebserviceForWb.setYxtywlsh(masterEntityKey);//原系统业务流水号
				ywWebserviceForWb.setTycxh((String)map.get("acceptNo"));//统一查询号
				ywWebserviceForWb.setCxmm((String)map.get("password"));//查询密码
				ywWebserviceForWb.setZjhhjgdm("空");
				ywWebserviceForWb = setJbrxmAndLxdhPart(templateCode, ywWebserviceForWb, map);
			}else{
				ywWebserviceForWb.setSendNotice("Y");
			}
			if("001".equals(link)){//受理
				ywWebserviceForWb.setSphjmc("受理");
				ywWebserviceForWb.setGdblsx(Long.parseLong(durationExpression.split(" ")[0]));//规定办理时限
				ywWebserviceForWb.setGdblsxdw("Z");//规定办理时限的单位
				if("jzfqwczzpf".equals(templateCode)){//排放收费
					ywWebserviceForWb.setGdsf("是");//规定收费///////////////////////////////
				}else{
					ywWebserviceForWb.setGdsf("否");//规定收费///////////////////////////////
				}				
				ywWebserviceForWb.setFlgdgxd("广州市");//法律规定管辖地/////////////////
				ywWebserviceForWb.setFsywgxd("广州市");//发生业务管辖地////////////////////////
				ywWebserviceForWb.setSljgzzjgdm("007482989");//受理机构组织机构代码//////////////////////////
				ywWebserviceForWb.setSljgmc("广州城市管理委员会");//受理机关名称//////////////////////////
				ywWebserviceForWb.setSldwblrxm(loginusername);//受理单位办理人姓名
				ywWebserviceForWb.setSldwblrgh("");//受理单位办理人工号
				ywWebserviceForWb.setSljtdd("广州城市管理委员会");//受理具体地点				
				ywWebserviceForWb.setSlsj(new Date());//受理时间
				String slzlqd = WfUtilsEX.getSlzlqd( Long.parseLong(masterEntityKey), templateCode, ywComSjcllistService, ywComSjclService);
				ywWebserviceForWb.setSlzlqd(StringUtils.isBlank(slzlqd)?"空":slzlqd);//受理资料清单
				if(StringUtils.isNotBlank(bslyy)){
					ywWebserviceForWb.setSlyf("N");//受理与否
				}else{
					ywWebserviceForWb.setSlyf("Y");//受理与否
				}
				ywWebserviceForWb.setBslyy(bslyy);//不受理原因
				ywWebserviceForWb.setTjfs("1");//提交方式（1-网上提交）				
			}else if("005".equals(link)){//办结
				ywWebserviceForWb.setSphjmc("办结");
				ywWebserviceForWb.setBjjgzzjgdm("007482989");//办结机关组织机构代码//////////////////////////
				ywWebserviceForWb.setBjjgmc("广州城市管理委员会");//办结机关名称//////////////////////////
				ywWebserviceForWb.setBjsj(new Date());//办结时间
				Map<String,String> bljgAndBljgmsMap = WfUtilsEX.getBljgAndBljgms(templateCode, masterEntityKey, ywPrintDocService);
				ywWebserviceForWb.setBjjg(bljgAndBljgmsMap.get("bljg"));//办结结果//////////////////////
				ywWebserviceForWb.setBljgms(bljgAndBljgmsMap.get("bljgms"));//办理结果描述
				ywWebserviceForWb.setZfthyy("");//作废或退回原因
				YwZhengwuInfo ywZhengwuInfo = new YwZhengwuInfo();
				ywZhengwuInfo = WfUtilsEX.setBsjgInfo(ywZhengwuInfo, ywPrintDocService, templateCode, masterEntityKey, map);
				ywWebserviceForWb.setZjmc(ywZhengwuInfo.getZjhpwmc());//证件/盖章名称
				ywWebserviceForWb.setZjbh(ywZhengwuInfo.getZjhpwbh());//证件编号
				String zjyxqx = "";
				if(StringUtils.isNotBlank(ywZhengwuInfo.getZjhpwyxqx())){
					if(ywZhengwuInfo.getZjhpwyxqx().contains("null")){
						zjyxqx = ywZhengwuInfo.getZjhpwyxqx().replace("null", "");
					}					
				}
				ywWebserviceForWb.setZjyxqx(zjyxqx);//证件有效期
				
				ywWebserviceForWb.setFzdw("");//发证/盖章单位
				if("jzfqwczzpf".equals(templateCode)){//排放收费
					String sfje = (String)map.get("sfje");
					if(StringUtils.isNotBlank(sfje)){
						if(sfje.contains("元")){
							ywWebserviceForWb.setSfje(sfje.split("元")[0]);//收费金额
						}else{
							ywWebserviceForWb.setSfje("0");//收费金额
						}
					}else{
						ywWebserviceForWb.setSfje("0");//收费金额
					}
				}else{
					ywWebserviceForWb.setSfje("0");//收费金额
				}				
				ywWebserviceForWb.setJedwdm("CNY");//金额单位代码
			}
			this.save(ywWebserviceForWb);
		}
	}
	
	/**
	 * 根据FeedbackMap获取xml字符串
	 * @param map
	 * @return
	 */
	public String getXmlStringByFeedbackMap(Map<String,String> map){
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement("feedback");
		for(String dataKey : map.keySet()){
			root.addElement(dataKey).addText(StringUtils.isBlank(map.get(dataKey))?"":map.get(dataKey));
		}
		return doc.asXML().toString();
	}
	
	/**
	 * 交换网办数据（受理、办结）
	 */
	public void exchangeYwWebserviceForWb(){
		List<YwWebserviceForWb> list = ywWebserviceForWbDao.getNoticeYwWebserviceForWb();
		System.out.println("list = "+list.size());
		if(list != null && list.size() > 0){
			for(int i = 0;i < list.size();i++){
				YwWebserviceForWb ywWebserviceForWb = list.get(i);
				Long id = ywWebserviceForWb.getId();
				String xmlString = "";
				String operation = "";
				System.out.println("ywWebserviceForWb.getSphjmc() = "+ywWebserviceForWb.getSphjmc());
				xmlString = getXmlStringByFeedbackMap(WfUtilsEX.buildMap(ywWebserviceForWb,"yyyy-MM-dd HH:mm:ss"));
				if("受理".equals(ywWebserviceForWb.getSphjmc())){//受理
					if("Y".equals(ywWebserviceForWb.getSendNotice())){//网上收案
						operation = "shouli";
					}else{//窗口收案
						operation = "shouli1";
					}
				}else{//办结
					if("Y".equals(ywWebserviceForWb.getSendNotice())){//网上收案
						operation = "banjie";
					}else{//窗口收案
						operation = "banjie1";
					}
				}
				System.out.println("xmlString = "+xmlString);
				Base64 base64 = new Base64();
				try {
					xmlString = new String(base64.encode(xmlString.getBytes("UTF-8")));
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				WSInvoker wsInvoker = new WSInvoker();
				try {
					ServiceResult serviceResult = null;
					String wsdl = wfServiceEX.getItemNameByItemCodeAndTypeCode("wbwsdl", "JK_WB_FX").getItemName();
					serviceResult = wsInvoker.invokeWS(wsdl,"WangBan_Synchronize_Service",operation, new Object[]{xmlString});
					System.out.println("serviceResult = "+serviceResult);
					System.out.println("return = "+serviceResult.getRetCode());
					System.out.println("serviceResult.getRetMessage() = "+serviceResult.getRetMessage());					
					if (serviceResult != null) {
						String flag = serviceResult.getRetCode(); //flag等于0，成功，flag等于1失败   成功就把状态改了
						if("0".equals(flag)){
							this.changState(id);
						}else if("1".equals(flag)){//失败，把交换次数保存到数据库，超过50次，则第二天再交换
							logger.error("(接口)网办数据交换接口异常:serviceResult.getRetCode()为1");
						}
					} else {
						logger.error("(接口)网办数据交换接口异常:serviceResult为空");
						System.out.println("WS invoked failed");
					}
				} catch (Exception e) {					
					logger.error("(接口)网办数据交换接口异常"+SysTraceLogWriter.MESSAGE_SEPARATOR + e.getMessage(), e);
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 如果是系统窗口收案，则要设置申请人字段部分，设置经办人姓名和联系电话
	 * @param ywWebserviceForWb
	 * @return
	 */
	public YwWebserviceForWb setJbrxmAndLxdhPart(String templateCode,YwWebserviceForWb ywWebserviceForWb,Map<String,String> map){
		if(templateCode.contains("jzljczz")){//处置证-运输
			ywWebserviceForWb.setSqrxm((String)map.get("ywlxr"));
			ywWebserviceForWb.setSqdwjbrsj((String)map.get("ywlxrtel"));
		}else if("shljcz".equals(templateCode)){//环卫-处置
			ywWebserviceForWb.setSqrxm((String)map.get("wtsfj"));
			ywWebserviceForWb.setSqdwjbrsj((String)map.get("lxdh"));
		}else if("ccgbggcs".equals(templateCode)){//公厕
			ywWebserviceForWb.setSqrxm((String)map.get("wtr"));
			ywWebserviceForWb.setSqdwjbrsj((String)map.get("sqrTel"));
		}else if("csdlwj".equals(templateCode)){//道路挖掘
			ywWebserviceForWb.setSqrxm((String)map.get("lxr"));
			ywWebserviceForWb.setSqdwjbrsj((String)map.get("jsdwTel"));
		}else if("csdllszysp".equals(templateCode)){//道路占用
			ywWebserviceForWb.setSqrxm((String)map.get("lxr"));
			ywWebserviceForWb.setSqdwjbrsj((String)map.get("sqdwTel"));
		}else if("shljqssj".equals(templateCode) || "shljys".equals(templateCode)){//环卫陆域或水域
			ywWebserviceForWb.setSqrxm((String)map.get("frdb"));
			ywWebserviceForWb.setSqdwjbrsj((String)map.get("lxdh"));
		}else if(templateCode.contains("jzfqwczzpf") || templateCode.contains("jzfqwczzxn")){//排放、消纳
			ywWebserviceForWb.setSqrxm((String)map.get("jsdwLxr"));
			ywWebserviceForWb.setSqdwjbrsj((String)map.get("jsdwLxrLxdh"));
		}else{//设施改动、企业资质、经营许可、户外广告
			ywWebserviceForWb.setSqrxm((String)map.get("ywlxr"));
			ywWebserviceForWb.setSqdwjbrsj((String)map.get("ywlxrtel"));
		}
		return ywWebserviceForWb;
	}
	
}
